<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>战争</title>
</head>
<body>
<canvas id="canvas" width="480" height="650"></canvas>
<script>
  // 定义宽和高
  var WIDTH = 480, HEIGHT = 650;
  // 定义状态
  var READED = 0,
      START = 1,
      RUNNING = 2,
      PAUSE = 3,
      OVER = 4;

  // 状态
  var state = READED;

  // 获取画布
  var canvas = document.getElementById('canvas'),
      context = canvas.getContext('2d');

  // 背景
  var SKY = {
    image: 'img/background.png',
    width: 480,
    height: 650,
    speed: 30
  };

  // 天空的业务对象
  var Sky = function (config) {
    // 创建图像对象
    var bg = new Image();
    bg.src = config.image

    this.bg = bg;
    this.width = config.width;
    this.height = config.height;
    this.speed = config.speed;

    this.x1 = 0;
    this.y1 = 0;
    this.x2 = 0;
    this.y2 = -this.height;
    this.lastTime = 0;

    /**
     * 移动背景的纵坐标
     */
    this.step = function () {
      // 是否到达天空的移动时间
      var currentTime = new Date().getTime();
      if (currentTime - this.lastTime >= this.speed) {
        this.y1++;
        this.y2++;
        this.lastTime = new Date().getTime();
      }
      // 是否超出范围
      this.y1 >= this.height && (this.y1 = -this.height);
      this.y2 >= this.height && (this.y2 = -this.height);
    };

    /**
     * 绘制图像
     * @param ctx context
     */
    this.paint = function (ctx) {
      ctx.drawImage(this.bg, this.x1, this.y1);
      ctx.drawImage(this.bg, this.x2, this.y2);
    };
  };

  // 创建对象
  var sky = new Sky(SKY);

  // 运行测试
  requestAnimationFrame(function step() {
    switch (state){
      case READED:
        // 天空
        sky.step();
        sky.paint(context);
        // copyright

        break;
      case START:
        // 准备开始
        break;
      case RUNNING:
        // 游戏进行中
        break;
      case PAUSE:
        // 暂停
        break;
      case OVER:
        // 游戏结束
        break;
    }
    requestAnimationFrame(step);
  });

</script>
<script src="js/main.js"></script>
</body>
</html>